# -*- coding: utf-8 -*-
"""
Created on Mon Jul 25 15:55:20 2022

@author: Ewing
"""

import pandas as pd
import os
import configparser
import logging
import logging.handlers
import sys

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QMessageBox, QApplication, QLabel
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Alignment, Side, Border


# config_file_path=sys.argv[1]
def run():
    if len(sys.argv) > 1:
        config_file_path = sys.argv[1]
    else:
        config_file_path = "config.ini"

    config = configparser.ConfigParser()
    config.read(config_file_path, encoding='utf-8')
    path = config.get("dic_path", "path")
    output_name = config.get("dic_path", "output_name")
    print("正在读取配置文件....")
    print("扫描路径:" + path)
    print("输出文件:" + output_name)
    print("正在执行脚本-1.多个文件名称提取成表格")
    os.chdir(path)
    # 1.读取图片文件夹路径
    # 2.建立空白excel文件“img.xlsx”
    writer = pd.ExcelWriter(output_name)
    # 3.将图片文件夹里的文件名写入新的列表
    # 3.1遍历图片文件夹
    for root, dirs, files in os.walk(path):
        # os.walk() 方法是一个简单易用的文件、目录遍历器，可以帮助我们高效的处理文件、目录方面的事情。
        # root 表示当前正在访问的文件夹路径
        # dirs 表示该文件夹下的子目录名list
        # files 表示该文件夹下的文件list
        list = []  # 建立新的列表list
        # 3.2遍历文件list里的所有的图片文件写入新列表list中
        for file in files:
            file = file.rstrip(".jpg")  # 将图片名末尾的“.jpg”去掉
            list.append(file)  # 将图片名加入新列表list中       
    # 4.将列表list嵌套进字典data中
    dict_ = {'filename': list}  # 键名为新建表格的字段名，值为以图片名为元素的列表
    # 5.转换成dataframe格式
    df = pd.DataFrame(dict_)
    # 6.储存在开始建立的excel中
    # df.to_excel(writer,'sheet1',startcol=0,index=False )
    # 工作表名称为“sheet1”，开始列为第一列，不需要索引
    # 7.保存文件
    # writer.save()
    print(df)
    df.to_excel(output_name)

    wb = load_workbook(output_name)
    # 打开工作表
    ws = wb.active

    # 调整列宽
    ws.column_dimensions['A'].width = 10
    ws.column_dimensions['B'].width = 10
    ws.column_dimensions['C'].width = 10
    ws.column_dimensions['D'].width = 10

    # 定义单元格样式
    '''
        #定义表头颜色为橙色
        header_fill=PatternFill('solid',fgColor='FF7F24')
            #定义表中颜色为浅黄色
        content_fill=PatternFill('solid',fgColor='FFFFE0')
            #定义表尾颜色为淡橘红色
        bottom_fill=PatternFill('solid',fgColor='EE9572')
    '''
    # 定义对其方式，纵向居中，横向居中
    align = Alignment(horizontal='center', vertical='center')

    # 定义边样式为细条
    side = Side('thin')
    # 定义表头边框样式有底边、右边
    head_border = Border(bottom=side, right=side)
    # 定义表中边框样式有左边
    content_border = Border(bottom=side, right=side, left=side, top=side)

    column = ws['A']
    mylist = [column[x].value for x in range(len(column))]

    i = 0
    for cell in column:
        cell.value = i
        i = i + 1
        # 取出第一行单元格
    for cell in ws[1]:
        # 设置单元格填充颜色
        # cell.fill=header_fill
        # 设置单元格对其方式
        cell.alignment = align
        # 设置单元格边框
        cell.border = head_border

        # 取出表中的各行,第二行到倒数第二行
    for row in ws.iter_rows(min_row=2, max_row=ws.max_row):
        for cell in row:
            # cell.fill=content_fill
            cell.alignment = align
            cell.border = content_border

    wb.save(output_name)

    print("get-pic-name.py : The job has been done successfully")
    return True


class win(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedWidth(180)
        self.setWindowTitle(" ")

        layout = QVBoxLayout()
        openConfig = QPushButton("打开配置", self)
        # openConfig.setText()
        # openTemplate = QPushButton("打开配置模板", self)
        # openTemplate.setText()
        startButton = QPushButton("运行", self)

        layout.addWidget(QLabel("多个文件名称提取成表格"))
        layout.addWidget(openConfig)
        # layout.addWidget(openTemplate)
        # layout.addStretch()
        layout.addWidget(startButton)

        self.setLayout(layout)
        openConfig.clicked.connect(self.openConfig)
        # openTemplate.clicked.connect(self.openTemplate)
        startButton.clicked.connect(self.start)

    def openConfig(self):
        if len(sys.argv) > 1:
            config_file_path = sys.argv[1]
        else:
            config_file_path = "config.ini"
        print(config_file_path)
        # print(len(sys.argv))
        os.system(config_file_path)
        pass

    def start(self):
        try:
            res = run()
        except Exception as e:
            print(repr(e))
            res = False

        if res:
            QMessageBox.information(self, "", "处理成功！")
        else:
            QMessageBox.critical(self, "", "处理失败，请查看后台日志！")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = win()
    main.show()
    sys.exit(app.exec())
